//
//  RecentListVIewController.m
//  SportSocial
//
//  Created by yull on 14/11/19.
//  Copyright (c) 2014年 yull. All rights reserved.
//

#import "RecentListVIewController.h"
#import "RecentCell.h"
#import "UIViewController+RESideMenu.h"
#import "RESideMenu.h"
#import "ChatInfoDao.h"
#import "ChatViewController.h"
#import "PrivateMsgSender.h"
#import "GroupMsgSender.h"
#import "RecentSystemCell.h"
#import "ChatSysInfoDao.h"
#import "SystemInfoViewController.h"
#import "PrivateMsgDao.h"
#import "GroupMsgDao.h"

@interface RecentListVIewController () <UITableViewDataSource,UITableViewDelegate,RecentBaseCellDelegate>

@property (nonatomic, strong) UITableView *recentTableView;

@property (nonatomic, strong) NSMutableArray *recentArray;

@end

@implementation RecentListVIewController

- (id)init
{
    if (self = [super init]) {
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationItem.title = @"最近联系的人";
    self.navigationController.navigationBar.titleTextAttributes = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,[UIFont systemFontOfSize:20.0f],NSFontAttributeName, nil];
    
    [self initSubViews];
    
    [self loadDataFromDB];
    [self initNaviItem];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadDataFromDB) name:@"ChatInfoReload" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onLogOut:) name:@"UserLogOut" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onReceive_User_Is_Delete:) name:@"user_is_deleted" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onReceive_Group_Is_Delete:) name:@"group_is_deleted" object:nil];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    self.recentTableView.delegate = nil;
    self.recentTableView.dataSource = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = NO;
}

- (void)initNaviItem
{
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 28, 26);
    [leftButton setImage:[UIImage imageNamed:@"title_icon1.png"] forState:UIControlStateNormal];
    [leftButton setImage:[UIImage imageNamed:@"title_icon1_selection.png"] forState:UIControlStateHighlighted];
    [leftButton addTarget:self action:@selector(showLeft:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    
    self.navigationItem.leftBarButtonItem = leftItem;
}

- (void)showLeft:(id)sender
{
    [self.sideMenuViewController presentLeftMenuViewController];
}

- (void)initSubViews
{
    CGRect rect = CGRectMake(0, 0, self.view.width, self.view.height-49-64);
    self.recentTableView = [[UITableView alloc] initWithFrame:rect];
    self.recentTableView.backgroundColor = [UIColor clearColor];
    self.recentTableView.delegate = self;
    self.recentTableView.dataSource = self;
    self.recentTableView.separatorInset = UIEdgeInsetsMake(0, 70, 0, 0);
    self.recentTableView.tableFooterView = [[UIView alloc] init];
    [self.view addSubview:self.recentTableView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger badgeNumber = 0;
    for (ChatInfo *chatInfo in self.recentArray) {
        badgeNumber += chatInfo.unReadCount;
    }
    
    if (badgeNumber) {
        self.navigationController.tabBarItem.badgeValue = [NSString stringWithFormat:@"%ld", (long)badgeNumber];
    } else {
        self.navigationController.tabBarItem.badgeValue = nil;
    }
    
    return self.recentArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [RecentBaseCell defaultCellHeight];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChatInfo *recent = [self.recentArray objectAtIndex:indexPath.row];
    static NSString *identifier = @"RecentChatCell";
    RecentCell *recentCell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!recentCell) {
        recentCell = [[RecentCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        recentCell.delegate = self;
    }
    [recentCell drawCellWithRecent:recent];
    return recentCell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    ChatInfo *chatInfo = [self.recentArray objectAtIndex:indexPath.row];
    
    BOOL ret = NO;
    if (chatInfo.infoType == ChatInfoTypeSystem) {
        ret = [[ChatSysInfoDao shareInstance] clearUnRead];
    }else {
        ret = [[ChatInfoDao shareInstance] clearUnReadCountWithChatInfo:chatInfo];
    }
    
    
    if (ret) {
        dispatch_async(dispatch_get_main_queue(), ^{
            chatInfo.unReadCount = 0;
            [tableView reloadData];
        });
    }
    
    if (chatInfo.infoType == ChatInfoTypePrivate) {
        UserModel *user = [[UserModel alloc] init];
        user.userId = chatInfo.privateId;
        user.icon = chatInfo.icon;
        user.sex = chatInfo.sex;
        user.name = chatInfo.name;
        
        ChatViewController *chatViewController = [[ChatViewController alloc] init];
        chatViewController.hidesBottomBarWhenPushed = YES;
        chatViewController.msgSender = [[PrivateMsgSender alloc] initWithUser:user];
        [self.navigationController pushViewController:chatViewController animated:YES];
    }else if (chatInfo.infoType == ChatInfoTypeGroup) {
        NearGroup *group = [[NearGroup alloc] init];
        group.group_id = chatInfo.groupId;
        group.icon = chatInfo.icon;
        group.name = chatInfo.name;
        
        ChatViewController *chatViewController = [[ChatViewController alloc] init];
        chatViewController.hidesBottomBarWhenPushed = YES;
        chatViewController.msgSender = [[GroupMsgSender alloc] initWithGroup:group];
        [self.navigationController pushViewController:chatViewController animated:YES];
    }else {
        SystemInfoViewController *systemViewController = [[SystemInfoViewController alloc] init];
        systemViewController.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:systemViewController animated:YES];
    }
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChatInfo *chatInfo = [self.recentArray objectAtIndex:indexPath.row];
    BOOL ret = NO;
    if (chatInfo.infoType == ChatInfoTypeSystem) {
        ret = [[ChatSysInfoDao shareInstance] clearSystemInfo];
    }else {
        ret = [[ChatInfoDao shareInstance] deleteChatInfo:chatInfo];
        
        if (chatInfo.infoType == ChatInfoTypePrivate) {
            ret &= [[PrivateMsgDao shareInstance] deleteAllMsgWithUserId:chatInfo.privateId];
        }else if (chatInfo.infoType == ChatInfoTypeGroup) {
            ret &= [[GroupMsgDao shareInstance] deleteAllMsgWithGroupId:chatInfo.groupId];
        }
    }
    
    if (ret) {
        [self.recentArray removeObject:chatInfo];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        });
    }
}

- (void)loadDataFromDB
{
    if (!self.recentArray) {
        self.recentArray = [NSMutableArray array];
    }else {
        [self.recentArray removeAllObjects];
    }
    
    [self.recentArray addObjectsFromArray:[[ChatInfoDao shareInstance] selectAlChatInfo]];
    
    ChatInfo *chatInfo = [[ChatSysInfoDao shareInstance] getTotalSystemInfo];
    if (chatInfo) {
        chatInfo.infoType = ChatInfoTypeSystem;
//        [self.recentArray addObject:chatInfo];
        [self.recentArray insertObject:chatInfo atIndex:0];
    }
    
    @weakify(self);
    dispatch_async(dispatch_get_main_queue(), ^{
        @strongify(self);
        [self.recentTableView reloadData];
    });
}

#pragma mark - RecentBaseCellDelegate
- (void)onClickRecentAvatarView:(ChatInfo *)chatInfo
{
    if (chatInfo.infoType == ChatInfoTypePrivate) {
        UIViewController *controller = [Interface createUserInfoViewControllerWithUserId:chatInfo.privateId userName:chatInfo.name];
        [self.navigationController pushViewController:controller animated:YES];
    } else if (chatInfo.infoType == ChatInfoTypeGroup) {
        
    }
}

#pragma mark - Notification
- (void)onReceive_User_Is_Delete:(NSNotification *)notification
{
    NSDictionary *dic = notification.userInfo;
    
    UInt64 userId = [[dic objectForKey:@"userid"] longLongValue];
    
    for (ChatInfo *chatInfo in self.recentArray) {
        if (chatInfo.infoType == ChatInfoTypePrivate && chatInfo.privateId == userId) {
            BOOL ret = [[ChatInfoDao shareInstance] deleteChatInfo:chatInfo];
            
            ret &= [[PrivateMsgDao shareInstance] deleteAllMsgWithUserId:chatInfo.privateId];
            
            if (ret) {
                [self.recentArray removeObject:chatInfo];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.recentTableView reloadData];
                });
            }
            
            break;
        }
    }
}

- (void)onReceive_Group_Is_Delete:(NSNotification *)notification
{
    NSDictionary *dic = notification.userInfo;
    
    UInt64 groupId = [[dic objectForKey:@"groupid"] longLongValue];
    
    for (ChatInfo *chatInfo in self.recentArray) {
        if (chatInfo.infoType == ChatInfoTypeGroup && chatInfo.groupId == groupId) {
            BOOL ret = [[ChatInfoDao shareInstance] deleteChatInfo:chatInfo];
            
            ret &= [[GroupMsgDao shareInstance] deleteAllMsgWithGroupId:groupId];
            
            if (ret) {
                [self.recentArray removeObject:chatInfo];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.recentTableView reloadData];
                });
            }
            
            break;
        }
    }
}

#pragma mark - 退出登录
- (void)onLogOut:(NSNotification *)notification
{
    [self.recentArray removeAllObjects];
    [self.recentTableView reloadData];
    
    UIViewController *controller = self.navigationController.viewControllers.firstObject;
    
    [self.navigationController setViewControllers:@[controller] animated:NO];
}

@end
